const eventListeners = [];

export async function registerEventListener(target, eventName, listener) {
    if (!target || !eventName || !listener) {
        return;
    }
    let _eventName = eventName;
    eventName = eventName.toLowerCase();
    for (let i = 0; i < eventListeners.length; i++) {
        let el = eventListeners[i];
        if (!el) {
            continue;
        }
        if (el.target === target && el.eventName === eventName) {
            el.listener = listener;
            return;
        }
    }
    eventListeners.push({target, eventName, listener});

    console.debug('--------registerEventListener--------');
    console.debug(`current register eventName:${_eventName}`);
    console.debug(`total event listeners count:${eventListeners.length}`);
    console.debug('--------registerEventListener--------');
}

export async function removeEventListener(target, eventName) {
    let _eventName = eventName;
    if (!target) {
        return;
    }
    if (eventName) {
        eventName = eventName.toLowerCase();
    }
    let removeIndex = [];
    for (let i = 0; i < eventListeners.length; i++) {
        let el = eventListeners[i];
        if (!el) {
            removeIndex.push(i);
            continue;
        }
        if (el.target !== target) {
            continue;
        }

        if (!eventName || (eventName && el.eventName === eventName)) {
            removeIndex.push(i);
            continue;
        }
    }
    if (removeIndex.length > 0) {
        removeIndex.forEach((index) => {
            eventListeners.splice(index, 1);
        });
    }
    console.debug('--------removeEventListener--------');
    console.debug(`current remove eventName:${_eventName}`);
    console.debug(`total event listeners count:${eventListeners.length}`);
    console.debug('--------removeEventListener--------');
}

export async function sendEvent(eventName, data) {
    if (!eventName) {
        return;
    }
    let _eventName = eventName;
    eventName = eventName.toLowerCase();
    let count = 0;
    for (let i = 0; i < eventListeners.length; i++) {
        let el = eventListeners[i];
        if (!el) {
            continue;
        }
        if (el.eventName === eventName) {
            count++;
            el.listener(data);
        }
    }
    console.debug('--------sendEvent--------');
    console.debug(`send event name:${_eventName}`);
    console.debug(`send event data:`);
    console.debug(data);
    console.debug(`send event listeners count:${count}`);
    console.debug('--------sendEvent--------');
}
